//
//  UIButton.swift
//  demo
//
//  Created by HAip on 2020/2/19.
//  Copyright © 2020 CodeYu. All rights reserved.
//

import Foundation

// 声明闭包,在外面使用时监听按钮的点击事件
typealias ButtonClick = (_ sender: UIButton) -> Void // 定义数据类型(其实就是设置别名)

extension UIButton{
        
        //MARK:  向外部提供可点击接口
        private struct AssociateRuntimeKey{
            static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue)

        }
        // 运行时关联
        var actionBlock: ButtonClick? {
          set {
            addTarget(self, action:#selector(tapped(button:)) , for:.touchUpInside)
            objc_setAssociatedObject(self, UIButton.AssociateRuntimeKey.actionBlock!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)

                }
          get {
            return objc_getAssociatedObject(self, UIButton.AssociateRuntimeKey.actionBlock!) as? ButtonClick
            }
           
       }
    
      /// 点击回调
         @objc private func tapped(button:UIButton) {
            actionBlock?(button)
            
         }
    
    
    
}


